import Vue from 'vue'
import Vuex from 'vuex'
import persistedstate from 'vuex-persistedstate'

import router from '@/router'
import { login } from '@/api'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    token: '',
    userInfo: {}
  },
  mutations: {
    saveToken: (state, token) => (state.token = token),
    saveUserInfo: (state, userInfo) => (state.userInfo = userInfo)
  },
  actions: {
    // ctx 上下文对象  payload 登录数据
    async loginAction(ctx, payload) {
      const data = await login(payload)
      // 保存数据到state
      if (data) {
        ctx.commit('saveToken', data.token)
        ctx.commit('saveUserInfo', data.user)

        router.replace('/profile')
      }
    }
  },
  plugins: [
    persistedstate({
      key: 'state'
    })
  ]
})
